import { useEffect, useState } from 'react'
import {
  OrderState,
  UpdateStatusReq,
  consignmentAPI,
  getOrderAPI,
  updateOrderStatusAPI,
} from '../../apis'

export interface OrderItem {
  id: string
  orderState: OrderState
}

export const useOrder = () => {
  const [orderList, setOrderList] = useState<OrderItem[]>([])

  const getOrderList = async () => {
    const res = await getOrderAPI({
      page: 1,
      pageSize: 10,
    })
    setOrderList(res.data.result.items)
  }

  useEffect(() => {
    getOrderList()
  }, [])

  // 恢复待发货
  const ship = async (reqParams: UpdateStatusReq) => {
    await updateOrderStatusAPI(reqParams)
    const { orderId } = reqParams
    const _orderList = [...orderList]
    const item = _orderList.find((item) => item.id === orderId)
    if (item) {
      item.orderState = 2
      setOrderList(_orderList)
    }
  }

  // 发货操作
  const consignment = async (id: string) => {
    await consignmentAPI(id)
    const _orderList = [...orderList]
    const item = _orderList.find((item) => item.id === id)
    if (item) {
      item.orderState = 3
      setOrderList(_orderList)
    }
  }

  return {
    orderList,
    ship,
    consignment,
  }
}
